#!/usr/bin/env python
import sys
sys.path.append("../Modules")
from ChomsPy import DAD
from Pygmund import Id
import cgi, json, cgitb, urllib

# ChomsPy CGI
print "Content-Type: application/json"
print ""

form = cgi.FieldStorage()

if "u" in form and "p" in form:
	u = urllib.unquote(form["u"].value)
	p = urllib.unquote(form["p"].value)
	db = DAD.Connect(Id.Init("../id/dad.conf").Get("CHOMSPY"), u, p)
	if "c" in form:
		# Command
		c = urllib.unquote(form["c"].value)
		if "d" in form:
			d = urllib.unquote(form["d"].value)
			d = d.strip()
			if d == "":
				print json.dumps(db.Command(c), indent=4)
			else:
				try:
					d = json.loads(d)
					print json.dumps(db.Command(c, d), indent=4)
				except ValueError:
					print json.dumps({ "error" : "No JSON data to Set"})
		else:
			print json.dumps(db.Command(c), indent=4)
	else:
		# No Command, error
		print json.dumps({"error" : "No Pragmatic provided."})
else:
	# No User/Password, error
	if "c" in form:
		# Get/List Command only (non-Private)
		c = urllib.unquote(form["c"].value)
		db = DAD.Connect(Id.Init("../id/dad.conf").Get("CHOMSPY"), "", "")
		print json.dumps(db.Command(c), indent=4)
	else:
		print json.dumps({"error" : "No Pragmatic provided"})

